layui.use(['layim','jquery','layer'], function(layim){
    var $ = jquery = layui.jquery,
        layer = layui.layer;
    var wsUri = "ws://chat.chenshiqi.com.cn:8081";

    //基础配置
    layim.config({

        //初始化接口
        init: {
            url: '/init_json.html'
            ,data: {}
        }

        //查看群员接口
        ,members: {
            url: '/getMembers.html'
            ,data: {}
        }

        //上传图片接口
        ,uploadImage: {
            url: '/uploadImg.html' //（返回的数据格式见下文）
            ,type: 'post' //默认post
        }

        //上传文件接口
        ,uploadFile: {
            url: '/uploadFile.html' //（返回的数据格式见下文）
            ,type: 'post' //默认post
        }

        ,isAudio: false //开启聊天工具栏音频
        ,isVideo: false //开启聊天工具栏视频

        //扩展工具栏
        ,tool: [{
            alias: 'code'
            ,title: '代码'
            ,icon: '&#xe64e;'
        }]

        //,brief: true //是否简约模式（若开启则不显示主面板）

        ,title: 'chat online' //自定义主面板最小化时的标题
        //,right: '100px' //主面板相对浏览器右侧距离
        //,minRight: '90px' //聊天面板最小化时相对浏览器右侧距离
        ,initSkin: '2.jpg' //1-5 设置初始背景
        //,skin: ['aaa.jpg'] //新增皮肤
        //,isfriend: false //是否开启好友
        //,isgroup: false //是否开启群组
//            ,min: true //是否始终最小化主面板，默认false
        ,notice: true //是否开启桌面消息提醒，默认false
        //,voice: false //声音提醒，默认开启，声音文件为：default.mp3

//            ,msgbox: layui.cache.dir + 'css/modules/layim/html/msgbox.html' //消息盒子页面地址，若不开启，剔除该项即可
//            ,find: layui.cache.dir + 'css/modules/layim/html/find.html' //发现页面地址，若不开启，剔除该项即可
        ,chatLog: layui.cache.dir + 'css/modules/layim/html/chatlog.html' //聊天记录页面地址，若不开启，剔除该项即可

    });

    websocket = new ReconnectingWebSocket(wsUri);

    websocket.onopen = function (evt) {
        websocket.send(JSON.stringify({'type':'open','user_id':user_id}));
    };
    websocket.onclose = function (evt) {
//            onClose(evt)
    };
    websocket.onmessage = function (evt) {
        var data = JSON.parse(evt.data);
        var type = data.type || '';
        var send_data = data.send_data || {};
        switch (type) {
            case 'open':
                layim.setFriendStatus(send_data.user_id, 'online');
                break;
            case 'receiveMessage':
                if(send_data.to.type == 'group'){
                    obj = {
                        username: send_data.mine.username
                        ,avatar: send_data.mine.avatar
                        ,id: send_data.to.id
                        ,type: send_data.to.type
                        ,content: send_data.mine.content
                        ,timestamp:send_data.to.timestamp
                    };
                }else{
                    obj = {
                        username: send_data.mine.username
                        ,avatar: send_data.mine.avatar
                        ,id: send_data.mine.id
                        ,type: send_data.to.type
                        ,content: send_data.mine.content
                        ,timestamp:send_data.to.timestamp
                    };
                }
                layim.getMessage(obj);
                break;
            case 'hide':
                layim.setFriendStatus(send_data.user_id, 'offline');
                break;
            case 'close':
                layim.setFriendStatus(send_data.user_id, 'offline');
                break;
        }
    };
    websocket.onerror = function (evt) {
//            onError(evt)
    };
    /*
    layim.chat({
      name: '在线客服-小苍'
      ,type: 'kefu'
      ,avatar: 'http://tva3.sinaimg.cn/crop.0.0.180.180.180/7f5f6861jw1e8qgp5bmzyj2050050aa8.jpg'
      ,id: -1
    });
    layim.chat({
      name: '在线客服-心心'
      ,type: 'kefu'
      ,avatar: 'http://tva1.sinaimg.cn/crop.219.144.555.555.180/0068iARejw8esk724mra6j30rs0rstap.jpg'
      ,id: -2
    });
    layim.setChatMin();*/

    //监听在线状态的切换事件
    layim.on('online', function(data){
        switch (data){
            case 'online':
                websocket.send(JSON.stringify({'type':'open','user_id':user_id}));
                break;
            case 'hide':
                websocket.send(JSON.stringify({'type':'hide','user_id':user_id}));
                break;
        }
    });

    //监听签名修改
    layim.on('sign', function(value){
        $.post('/editSign.html',{sign:value},function(re){});
    });

    //监听自定义工具栏点击，以添加代码为例
    layim.on('tool(code)', function(insert){
        layer.prompt({
            title: '插入代码'
            ,formType: 2
            ,shade: 0
        }, function(text, index){
            layer.close(index);
            insert('[pre class=layui-code]' + text + '[/pre]'); //将内容插入到编辑器
        });
    });

    //监听layim建立就绪
    layim.on('ready', function(res){
        $.get('/getChatLog.html','',function (re) {
            if(re.code == 0){
                var data = re.data;
                var chat_log = {};
                var friend_chatlog_count = Object.keys(data.friend_chatlog_count);
                var group_chatlog_count = Object.keys(data.group_chatlog_count);
                if(friend_chatlog_count.length > 0) {
                    $.each(data.friend_chatlog_count, function (i, count) {
                        if(count>0){
                            if(layui.layim.cache().local.chatlog && layui.layim.cache().local.chatlog['friend'+i]){
                                delete layui.layim.cache().local.chatlog['friend'+i];
                            }
                            $.each(data.friend_chatlog[i],function (n,log) {
                                chat_log = JSON.parse(log);
                                console.log(chat_log);
                                obj = {
                                    username: chat_log.mine.username
                                    ,avatar: chat_log.mine.avatar
                                    ,id: chat_log.mine.id
                                    ,type: chat_log.to.type
                                    ,content: chat_log.mine.content
                                    ,timestamp:chat_log.to.timestamp
                                };
                                if(chat_log.mine.id != user_id){
                                    layim.getMessage(obj);
                                }
                            })
                        }
                    });
                }
                if(group_chatlog_count.length > 0) {
                    $.each(data.group_chatlog_count, function (i, count) {
                        if(count>0){
                            if(layui.layim.cache().local.chatlog && layui.layim.cache().local.chatlog['group'+i]) {
                                delete layui.layim.cache().local.chatlog['group' + i];
                            }
                            $.each(data.group_chatlog[i], function (n, log) {
                                chat_log = JSON.parse(log);
                                console.log(chat_log);
                                obj = {
                                    username: chat_log.mine.username
                                    , avatar: chat_log.mine.avatar
                                    , id: chat_log.to.id
                                    , type: chat_log.to.type
                                    , content: chat_log.mine.content
                                    , timestamp: chat_log.to.timestamp
                                };
                                if (chat_log.mine.id != user_id) {
                                    layim.getMessage(obj);
                                }
                            })
                        }
                    });
                }
            }else{
                layer.msg(re.message, {
                    time: 1000, //1s后自动关闭
                });
                setTimeout(function () {
                    location.href = "/login.html";
                },1000);
            }
        });

        layim.msgbox(5); //模拟消息盒子有新消息，实际使用时，一般是动态获得

        //添加好友（如果检测到该socket）
//            layim.addList({
//                type: 'group'
//                ,avatar: "http://tva3.sinaimg.cn/crop.64.106.361.361.50/7181dbb3jw8evfbtem8edj20ci0dpq3a.jpg"
//                ,groupname: 'Angular开发'
//                ,id: "12333333"
//                ,members: 0
//            });
//            layim.removeList({
//                type: 'friend'
//                ,groupid: 1
//                ,id: "3"
//            });

//            setTimeout(function(){
        //接受消息（如果检测到该socket）
//                layim.getMessage({
//                    username: "Hi"
//                    ,avatar: "http://qzapp.qlogo.cn/qzapp/100280987/56ADC83E78CEC046F8DF2C5D0DD63CDE/100"
//                    ,id: "10000111"
//                    ,type: "friend"
//                    ,content: "临时："+ new Date().getTime()
//                });

        /*layim.getMessage({
          username: "贤心"
          ,avatar: "http://tp1.sinaimg.cn/1571889140/180/40030060651/1"
          ,id: "100001"
          ,type: "friend"
          ,content: "嗨，你好！欢迎体验LayIM。演示标记："+ new Date().getTime()
        });*/

//            }, 3000);
    });

    //监听发送消息
    layim.on('sendMessage', function(data){
        var To = data.to;
        data.to.timestamp = new Date().getTime();
        websocket.send(JSON.stringify({'type':'sendMessage','data':data}));

//            if(To.type === 'friend'){
//                layim.setChatStatus('<span style="color:#FF5722;">对方正在输入。。。</span>');
//            }
//            return false;
        //演示自动回复
//            setTimeout(function(){
//                var obj = {};
//                if(To.type === 'group'){
//                    obj = {
//                        username: '模拟群员'+(Math.random()*100|0)
//                        ,avatar: layui.cache.dir + 'images/face/'+ (Math.random()*72|0) + '.gif'
//                        ,id: To.id
//                        ,type: To.type
//                        ,content: autoReplay[Math.random()*9|0]
//                    }
//                } else {
//                    obj = {
//                        username: To.name
//                        ,avatar: To.avatar
//                        ,id: To.id
//                        ,type: To.type
//                        ,content: autoReplay[Math.random()*9|0]
//                    }
//                    layim.setChatStatus('<span style="color:#FF5722;">在线</span>');
//                }
//                layim.getMessage(obj);
//            }, 1000);
    });

    //监听查看群员
    layim.on('members', function(data){
        //console.log(data);
    });

    //监听聊天窗口的切换
    layim.on('chatChange', function(res){
        var type = res.data.type;
        var status = res.data.status;
        console.log($('.layim-'+type+res.data.id +' .layim-msg-status'));
        if(type == 'friend' && res.data.id == user_id){
            layer.msg('不可以和自己对话', {
                time: 1000, //1s后自动关闭
            });
            $('.layim-chatlist-friend'+user_id).children('i').click();
        }
        if(type === 'friend'){
            //模拟标注好友状态
            if(status === 'online'){
                layim.setChatStatus('<span style="color:#FF5722;">在线</span>');
            }else{
                layim.setChatStatus('<span>离线</span>');
            }
        } else if(type === 'group'){
            $('.layim-chat-group.layui-show .layim-chat-members').html(res.data.group_count+'人');
            //模拟系统消息
//                layim.getMessage({
//                    system: true
//                    ,id: res.data.id
//                    ,type: "group"
//                    ,content: '模拟群员'+(Math.random()*100|0) + '加入群聊'
//                });
        }

        if($('.layim-'+type+res.data.id +' .layim-msg-status').hasClass('layui-show')){
            $.post('/setAlreadyRead.html',{type:type,to_id:res.data.id},function (re) {
                if(re.code == -1){
                    layer.msg(re.message, {
                        time: 1000, //1s后自动关闭
                    });
                    setTimeout(function () {
                        location.href = "/login.html";
                    },1000);
                }else if(re.code == -2){
                    layer.msg(re.message, {
                        time: 1000, //1s后自动关闭
                    });
                }
            });
        }
    });

    layim.on('showMyInfo',function (re) {
        console.log(123);
    });

});

function logout() {
    $.get('/logout','',function(re){
        layer.msg(re.message, {
            time: 1000, //1s后自动关闭
        });
        setTimeout(function () {
            location.href = "/login.html";
        },1000);
    });
}